import React, { useRef, useState, useEffect } from 'react';
import type { TableProps } from 'antd';
import { Table, Card, Form, Select, Button } from 'antd';
import { getAll } from '@/services/StudentAnalysisCounsellor';
import { ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import styles from './index.less';
import type {
  ColumnsType,
  FilterValue,
  SorterResult,
} from 'antd/es/table/interface';
import { useMount } from 'ahooks';
import { FormInstance } from 'antd/lib/form';
import AnalysisAchievement from './AnalysisAchievement';
import { connect } from 'umi';

interface DataType {
  key: React.Key;
  id: React.Key;
  stuName: string;
  stuNumber: string;
  className: string;
  grade: string;
  major: string;
  classAdvisor: string;
  score: number;
  gpa: number;
  credit: number;
  majorRank: number;
}

const AllScoreList: React.FC<any> = (props) => {
  const [filteredInfo, setFilteredInfo] = useState<
    Record<string, FilterValue | null>
  >({});
  const [sortedInfo, setSortedInfo] = useState<SorterResult<DataType>>({});
  const [records, setRecords] = useState<any>([]);
  const [res, setRes] = useState<any>([]);
  const formRef = useRef<FormInstance>(null);
  const onClick = (record: any) => {
    // console.log(JSON.stringify(record))
    props.add({
      key: '1',
      name: record.stuName,
      stuNumber: record.stuNumber,
    });
  };

  // 在获取数据后，添加序号字段
  const addSerialNumber = (data: DataType[]) => {
    return data.map((item, index) => {
      return {
        ...item,
        id: index + 1,
      };
    });
  };

  // const getAllList = async () => {
  //   try {
  //     let token: any = localStorage.getItem('token');
  //     const res = await getAll(
  //       token,
  //       JSON.parse(props.user.user.currrentuser).account,
  //     );
  //     if (res?.data?.data) {
  //       const modifiedData = addSerialNumber(res?.data.data);
  //       setRecords(modifiedData);
  //     } else {
  //     }
  //   } catch (error) {}
  // };
  const getAllList = () => {
    if (props.dispatch) {
      props.dispatch({
        //路径：model的namespace+effects函数名
        type: 'Model_StudentAnalysisStudentModel/getStudentScoreEffect',
        payload: {
          data: JSON.parse(props.user.currrentuser).account,
          callback: (value: any) => {
            console.log(value);
            setRecords(value);
          },
        },
      });
    }
  };
  useEffect(() => {
    if (props.user.currrentuser.length != 0) {
      console.log(JSON.parse(props.user.currrentuser));
      getAllList();
    }
  }, [props]);
  const handleChange: TableProps<DataType>['onChange'] = (
    pagination,
    filters,
    sorter,
  ) => {
    console.log('Various parameters', pagination, filters, sorter);
    setFilteredInfo(filters);
    setSortedInfo(sorter as SorterResult<DataType>);
  };
  //筛选
  const searchOnFinish = async (values: any) => {
    // 获取表单值
    let stuName = values.stuName;
    let className = values.className;
    let grade = values.grade;
    let major = values.major;
    let classAdvisor = values.classAdvisor;
    //过滤逻辑
    setRes(records);
    let filteredData = records.filter((item: DataType) => {
      if (stuName && !item.stuName.includes(stuName)) {
        return false;
      }
      if (className && !item.className.includes(className)) {
        return false;
      }
      if (grade && !item.grade.includes(grade)) {
        return false;
      }
      if (major && !item.major.includes(major)) {
        return false;
      }
      if (classAdvisor && !item.classAdvisor.includes(classAdvisor)) {
        return false;
      }
      return true;
    });

    setRecords(filteredData);
  };

  //重置
  const handleReset = () => {
    formRef.current?.resetFields();
    setRecords(res); // 重置为初始数据
  };
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'stuName',
      key: 'stuName',
      //render 属性接收一个函数，该函数有两个参数，第一个参数 _ 是当前单元格的值（在这里没有使用），第二个参数 record 是当前行的数据对象。
      render: (_, record) => (
        <a
          onClick={() => {
            onClick(record);
          }}
        >
          {record.stuName}
        </a>
      ),
    },
    {
      title: '学号',
      dataIndex: 'stuNumber',
      key: 'stuNumber',
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className',
    },
    {
      title: '年级',
      dataIndex: 'grade',
      key: 'grade',
    },
    {
      title: '专业',
      dataIndex: 'major',
      key: 'major',
      filters: [
        { text: 'Joe', value: 'Joe' },
        { text: 'Jim', value: 'Jim' },
      ],
      filteredValue: filteredInfo.name || null,
      onFilter: (value: string, record) => record.major.includes(value),
    },
    {
      title: '班导师',
      dataIndex: 'classAdvisor',
      key: 'classAdvisor',
      onFilter: (value: string, record) => record.major.includes(value),
    },
    {
      title: '平均成绩',
      dataIndex: 'score',
      key: 'score',
      sorter: (a, b) => a.score - b.score,
      sortOrder: sortedInfo.columnKey === 'score' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '平均学分绩点',
      dataIndex: 'gpa',
      key: 'gpa',
      sorter: (a, b) => a.gpa - b.gpa,
      sortOrder: sortedInfo.columnKey === 'gpa' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '加权学分成绩',
      dataIndex: 'credit',
      key: 'credit',
      sorter: (a, b) => a.credit - b.credit,
      sortOrder: sortedInfo.columnKey === 'credit' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: '排名',
      dataIndex: 'majorRank',
      key: 'majorRank',
      sorter: (a, b) => a.majorRank - b.majorRank,
      sortOrder: sortedInfo.columnKey === 'majorRank' ? sortedInfo.order : null,
      ellipsis: true,
    },
  ];

  // useMount(() => {
  //   getAllList();
  // });
  return (
    <div>
      <div>
        <Card
          title={
            <span style={{ fontWeight: 'bold', fontSize: 18 }}>
              全部成绩列表
            </span>
          }
        >
          <ProForm
            layout="inline"
            onFinish={searchOnFinish}
            onReset={handleReset}
          >
            <ProFormText
              label="姓名"
              name="stuName"
              placeholder="请输入学生姓名"
              width={160}
            />
            <ProFormText
              label="班级"
              name="className"
              placeholder="请输入班级"
              width={160}
            />
            <ProFormText
              label="年级"
              name="grade"
              placeholder="请输入年级"
              width={160}
            />
            <ProFormText
              label="专业"
              name="major"
              placeholder="请输入专业"
              width={160}
            />
            <ProFormText
              label="班导师"
              name="instructorName"
              placeholder="请输入班导师"
              width={160}
            />
          </ProForm>
        </Card>
      </div>
      <div>
        <Card>
          <Table
            columns={columns}
            dataSource={records}
            onChange={handleChange}
          />
        </Card>
      </div>
      <AnalysisAchievement />
    </div>
  );
};
export default connect(({ Model_StudentAnalysisStudentModel, user }: any) => ({
  user,
  Model_StudentAnalysisStudentModel,
}))(AllScoreList);
